# -*- coding: utf-8 -*-
# @Time    : 2023/9/20 10:30
# @Author  : Jonny
# @File    : LuckMqService.py
# @Describe: MQ钉钉消息提醒服务层
import json
import time
import base64
import requests

from LuckDingtalkService import LuckDingtalkService
from LuckDingtalkUserService import LuckDingtalkUserService
from LuckMqQueueService import LuckMqQueueService
from LuckMqMsgService import LuckMqMsgService


class LuckMqService1(object):
    def __init__(self, config):
        self.config = config

    CONTENT_TYPE = 'application/json'
    # 采集MQ队列信息
    def read_queues(self):
        for mq_rpc_api_obj in self.config["mq_rpc_api_list"]:
            try:
                # 1.发送GET请求，读取当前要采集的队列
                auth = str(base64.b64encode(
                    f'{self.config["mq_rpc_api_basic_auth1"]}:{self.config["mq_rpc_api_basic_auth2"]}'.encode('utf-8')),'utf-8')
                headers = {
                    'Content-Type': self.CONTENT_TYPE,
                    'Authorization': f'Basic {auth}'
                }
                response = requests.get(f'{mq_rpc_api_obj["mq_rpc_api"]}/readQueues', headers=headers)
                # 解析JSON响应
                rpc_data = response.json()
                data = rpc_data["data"]
                mq_config = rpc_data["config"]
                queues = self.convert_queues(data)
                mq_data_unacknowledged = queues["mq_data_unacknowledged"]

                mq_queue = LuckMqQueueService(self.config)

                # 2.读取当前采集地址已存储到表中异常队列数据
                parameters = {
                    "mq_url": mq_rpc_api_obj["mq_rpc_api"]
                }
                list = mq_queue.read(parameters)
                data = list["data"]

                data_exist = []
                data_no_exist = []
                # 3.和当前采集地址采集的异常队列进行比较，找出在表中不存在和存在的异常队列数据
                for d in data:
                    b_has = False
                    for row in mq_data_unacknowledged:
                        if d["vhost"] == row["vhost"] and d["name"] == row["name"]:
                            b_has = True
                            break
                    if b_has:
                        data_exist.append(d)
                    else:
                        data_no_exist.append(d)
                print("data_exist", data_exist)
                print("data_no_exist", data_no_exist)
                # 4.存在时，说明队列未被消费，插入待发送异常消息记录表中；不存在时，说明队列已被正常消费，插入待发送恢复消息记录表中
                # self.send_msg_by_dingtalk(data_exist)
                mq_msg = LuckMqMsgService(self.config)
                for row in data_exist:
                    parameters = {
                        "type": 0,  # 类型（0异常/1正常）
                        "state": 0,  # 发送状态（0未发送/1已发送）
                        "mq_url": row["mq_url"],
                        "vhost": row["vhost"],
                        "name": row["name"]
                    }
                    msgs = mq_msg.read(parameters)
                    if len(msgs["data"]) <= 0:
                        parameters = {
                            "type": 0,  # 类型（0异常/1正常）
                            "state": 0,  # 发送状态（0未发送/1已发送）
                            "userid": row["userid"],
                            "mq_name": row["mq_name"],
                            "mq_url": row["mq_url"],
                            "mq_config": row["mq_config"],
                            "vhost": row["vhost"],
                            "note": row["note"],
                            "name": row["name"],
                            "descr": row["descr"]
                        }
                        mq_msg.add(parameters)

                for row in data_no_exist:
                    parameters = {
                        "type": 1,  # 类型（0异常/1正常）
                        "state": 0,  # 发送状态（0未发送/1已发送）
                        "mq_url": row["mq_url"],
                        "vhost": row["vhost"],
                        "name": row["name"]
                    }
                    msgs = mq_msg.read(parameters)
                    if len(msgs["data"]) <= 0:
                        parameters = {
                            "type": 1,  # 类型（0异常/1正常）
                            "state": 0,  # 发送状态（0未发送/1已发送）
                            "userid": row["userid"],
                            "mq_name": row["mq_name"],
                            "mq_url": row["mq_url"],
                            "mq_config": row["mq_config"],
                            "vhost": row["vhost"],
                            "note": row["note"],
                            "name": row["name"],
                            "descr": row["descr"]
                        }
                        mq_msg.add(parameters)

                # 5.删除当前采集地址已保存的异常数据
                mq_queue.delete({
                    "mq_url": mq_rpc_api_obj["mq_rpc_api"]
                })

                # 6.将本次采集地址采集的数据添加到表中
                for row in mq_data_unacknowledged:
                    parameters = {
                        "state": 0,  # 发送状态（0未发送/1已发送）
                        "userid": row["userid"],
                        "mq_name": mq_config["mq_name"],
                        "mq_url": mq_rpc_api_obj["mq_rpc_api"],
                        "mq_config": json.dumps(mq_config, ensure_ascii=False),
                        "vhost": row["vhost"],
                        "note": row["label"],
                        "name": row["name"],
                        "descr": row["count"]
                    }
                    mq_queue.add(parameters)

            except Exception as e:
                print(f'采集MQ队列信息 {mq_rpc_api_obj["mq_rpc_api"]} 异常：{e}')
                robot_service = LuckDingtalkService(self.config)
                robot_service.send_link_msg_to_group('连接RabbitMQ采集地址异常', f'{mq_rpc_api_obj["mq_rpc_api"]} 请及时排查', mq_rpc_api_obj["mq_rpc_api"])

    # 发送消息
    def send_msg(self):
        for mq_rpc_api_obj in self.config["mq_rpc_api_list"]:
            mq_msg = LuckMqMsgService(self.config)
            parameters = {
                "type": 0,  # 类型（0异常/1正常）
                "state": 0,  # 发送状态（0未发送/1已发送）
                "mq_url": mq_rpc_api_obj["mq_rpc_api"]
            }
            msgs = mq_msg.read(parameters)
            data = msgs["data"]
            try:
                # 发送异常消息
                self.send_msg_by_dingtalk(data, "未消费")

                # 修改为已发送状态
                for d in data:
                    parameters = {
                        "id": d["id"],
                        "state": 1  # 发送状态（0未发送/1已发送）
                    }
                    mq_msg.update(parameters)
            except Exception as e:
                print(f"发送消息异常：{e}")
            """
            parameters = {
                "type": 1,  # 类型（0异常/1正常）
                "state": 0,  # 发送状态（0未发送/1已发送）
                "mq_url": mq_rpc_api_obj["mq_rpc_api"]
            }
            msgs = mq_msg.read(parameters)
            data = msgs["data"]
            try:
                # 发送异常消息
                self.send_msg_by_dingtalk(data, "已恢复")

                # 修改为已发送状态
                for d in data:
                    parameters = {
                        "id": d["id"],
                        "state": 1  # 发送状态（0未发送/1已发送）
                    }
                    mq_msg.update(parameters)
            except Exception as e:
                print(f"发送消息异常：{e}")
            """

    # 通过钉钉发送消息
    def send_msg_by_dingtalk(self, data, state):
        try:
            robot_service = LuckDingtalkService(self.config)
            user_service = LuckDingtalkUserService(self.config)
            dingtalk_robot_msg_type = self.config["dingtalk_robot_msg_type"]
            index = 0
            for row in data:
                index = index + 1
                userid = row["userid"]
                mq_config = row["mq_config"]
                mq_config = json.loads(mq_config)

                # 读取指定用户信息
                usernames = []
                userids = []
                recipient = ""
                if userid != "":
                    arr_userid = userid.split(",")
                    for uid in arr_userid:
                        if "user_job_number" == self.config["dingtalk_user_filter_type"]:
                            user_info = user_service.read_user_by_gh(uid)
                        else:
                            user_info = user_service.read_user_by_id(uid)

                        if user_info is not None:
                            usernames.append("@" + user_info["user_name"])
                            userids.append(user_info["user_id"])
                    if usernames:
                        username = " ".join(usernames)
                        userid = ",".join(userids)
                        recipient = userid

                if "text" == dingtalk_robot_msg_type:
                    dingtalk_content = {
                        "content": f" ● 序号：{index} \n ● 系统：{row['note']} \n ● VHost：{row['vhost']} \n ● 队列：{row['name']} \n ● 数量：{row['descr']} \n ● 状态：{state} \n ● 时间：{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))} \n ● MQ名称：{mq_config['mq_name']} \n ● MQ地址：{mq_config['mq_url']}"
                    }
                    print("dingtalk_content", dingtalk_content)
                    robot_service.send_text_msg_to_group(dingtalk_content, recipient)
                elif "markdown" == dingtalk_robot_msg_type:
                    dingtalk_content = {
                        "title": f"{mq_config['mq_name']} {mq_config['mq_url']}",
                        "text": f" - **序号**：{index} \n- **系统**：{row['note']} \n - **VHost**：{row['vhost']} \n - **队列**：{row['name']} \n - **数量**：{row['descr']} \n - **状态**：{state} \n - **时间**：{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))} \n - **MQ名称**：{mq_config['mq_name']} \n - **MQ地址**：{mq_config['mq_url']}"
                    }
                    if "all" != userid:
                        dingtalk_content["text"] += f"\n - {username}"

                    print("dingtalk_content", dingtalk_content)
                    robot_service.send_markdown_msg_to_group(dingtalk_content, recipient)
        except Exception as e:
            raise e

    def convert_queues(self, data):
        # 包含
        mq_application_inclusions_list = self.config["mq_application_inclusions_list"]
        new_data1 = []
        if len(mq_application_inclusions_list) > 0:
            for item in data:
                for mq_application_inclusions in mq_application_inclusions_list:
                    if mq_application_inclusions in item["name"]:
                        new_data1.append(item)
                        break
        else:
            new_data1 = data

        # 不包含
        mq_application_exclusions_list = self.config["mq_application_exclusions_list"]
        new_data2 = []
        if len(mq_application_exclusions_list) > 0:
            for item in new_data1:
                if all(mq_application_exclusions not in item["name"] for mq_application_exclusions in mq_application_exclusions_list):
                    new_data2.append(item)
        else:
            new_data2 = new_data1
        # print("new_data2", new_data2)
        mq_data_ready = []
        mq_data_unacknowledged = []
        for item in new_data2:
            if item["messages_ready"] > 0:
                # 翻译成对应子系统
                label = ''
                userid = 'all'
                for dic in self.config["mq_application_list"]:
                    if dic["name"] in item["name"]:
                        label = dic["label"]
                        userid = dic["userid"]
                        break

                messages_ready_dict = {
                    "vhost": item["vhost"],
                    "name": item["name"],
                    "userid": userid,
                    "label": label,
                    "count": item["messages_ready"]
                }
                mq_data_ready.append(messages_ready_dict)
            if item["messages_unacknowledged"] > 0:
                # 翻译成对应子系统
                label = ''
                userid = 'all'
                for dic in self.config["mq_application_list"]:
                    if dic["name"] in item["name"]:
                        label = dic["label"]
                        userid = dic["userid"]
                        break

                messages_unacknowledged_dict = {
                    "vhost": item["vhost"],
                    "name": item["name"],
                    "userid": userid,
                    "label": label,
                    "count": item["messages_unacknowledged"]
                }
                mq_data_unacknowledged.append(messages_unacknowledged_dict)

        data_dict = {
            "mq_data_ready": mq_data_ready,
            "mq_data_unacknowledged": mq_data_unacknowledged
        }
        return data_dict
